import subprocess
import streamlit as st
from back_end.helpers import utils
from back_end.hsa.data_display.bar_chart import BarChart
from back_end.hsa.data_display.word_cloud import WordCloud
from back_end.hsa.data_display.line_chart import LineChart

def launch_page():
    args = ["streamlit", "run", __file__]
    subprocess.run(args, env=utils.get_pythonpath_env())

def render_chart(title, chart_key, plot_func, time_options, default_index=0):
    st.header(title)
    time_range = st.selectbox(f'选择{title}时间范围', time_options, default_index)
    update_chart(chart_key, plot_func, time_range)
    display_chart(chart_key)

def update_chart(chart_key, plot_func, time_range):
    if st.session_state.get(f'last_{chart_key}_time_range') == time_range:
        return
    st.session_state[f'last_{chart_key}_time_range'] = time_range
    st.session_state[chart_key] = plot_func(time_range)

def display_chart(chart_key):
    if chart_key == 'word_cloud':
        st.markdown(f'<div>{st.session_state[chart_key]}</div>', unsafe_allow_html=True)
    else:
        st.altair_chart(st.session_state[chart_key], use_container_width=True)

if __name__ == "__main__":
    st.title('海关报关数据展示平台')
    render_chart('词云', 'word_cloud', WordCloud.plot, ['日', '周', '月', '年'], 3)
    render_chart('柱状图', 'bar_chart', BarChart.plot, ['日', '周', '月', '年'], 3)
    render_chart('折线图', 'line_chart', LineChart.plot, ['周', '月', '年'], 2)
